package com.lmx.persistence.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.lmx.common.constants.CommonConstants;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Activity;
import com.lmx.repoDomain.tmodel.DeviceType;
import com.lmx.repoDomain.tmodel.DeviceTypeItem;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.DicttypeTenant;
import com.lmx.repoDomain.tmodel.Typegroup;

/**
 * 字典表service
 *
 * @author ytche
 * @date 2017年4月27日
 *
 */
@Service
@Scope("prototype")
public class DicttypeService {
	private Log logger = LogFactory.getLog(this.getClass());

	@Autowired
	private GenericService<Dicttype> dslservice;
	@PersistenceContext
	private EntityManager em;
	@Autowired
	private DicttypeTenantService typeTenantSrv;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private CustomerVipInfoService vipInfoService;

	/**
	 * 根据id获取字典表的typecode
	 *
	 * @author ytche
	 * @param id
	 * @return
	 * @date 2017年3月31日 下午3:48:01
	 */
	public String findCodeById(Long id) {
		String rtn = "";
		String queryStr = "select * from Dicttype where id = ?1 and delStatus =0";
		List<Dicttype> dic = this.em.createQuery(queryStr).setParameter(1, id)
				.getResultList();
		if (dic != null && dic.size() > 0) {
			rtn = dic.get(0).getTypecode();
		}
		return rtn;
	}

	/**
	 * 获取租户个人字典表
	 *
	 * @author ytche
	 * @param tenantId
	 * @return
	 * @date 2017年4月6日 下午5:00:55
	 */
	public Iterable<Dicttype> findDicTypeOfTenant(Long tenantId) {
		List<Dicttype> rtn = Lists.newArrayList();
		List<DicttypeTenant> tenantList = this.typeTenantSrv
				.findByTenantId(tenantId);
		if (tenantList == null || tenantList.size() == 0) {
			return rtn;
		}
		for (DicttypeTenant dicttypeTenant : tenantList) {
			Dicttype dicttype = new Dicttype();
			BeanUtils.copyProperties(dicttypeTenant, dicttype);
			if (dicttypeTenant.getTypegroupTenant() != null) {
				Typegroup typegroup = new Typegroup();
				BeanUtils.copyProperties(dicttypeTenant.getTypegroupTenant(),
						typegroup);
				dicttype.setTypegroup(typegroup);
			}
			rtn.add(dicttype);
		}
		return rtn;
	}

	/**
	 * 获取该分组的所有字典值
	 *
	 * @author ytche
	 * @param code
	 * @return
	 * @date 2017年5月17日 下午5:33:26
	 */
	public List<Dicttype> findByGroupCode(String code) {
		String queryStr = "select dic from Dicttype as dic where dic.typegroup.typegroupcode = ? and dic.delStatus= 0";
		return this.em.createQuery(queryStr).setParameter(1, code)
				.getResultList();
	}

	public Dicttype findById(Long id) {
		this.dslservice.setEntityClass(Dicttype.class);
		return (Dicttype) this.dslservice.findById(id);
	}

	public Dicttype findByCode(String typeCode) {
		String queryStr = "select dic from Dicttype as dic where dic.typecode =? and dic.delStatus= 0 ";
		List<Dicttype> list = this.em.createQuery(queryStr)
				.setParameter(1, typeCode).getResultList();
		return list == null || list.size() < 1 ? null : list.get(0);
	};

	/**
	 * 同typegroup下的Dicttype名称不能相同
	 */
	public Dicttype findByName(Dicttype model) {
		String queryStr = "select dic from Dicttype as dic where dic.typename =?1 and dic.delStatus= 0 and dic.typegroup.typegroupcode=?2";
		List<Dicttype> list = this.em.createQuery(queryStr)
				.setParameter(1, model.getTypename())
				.setParameter(2, model.getTypegroup().getTypegroupcode())
				.getResultList();
		return list == null || list.size() < 1 ? null : list.get(0);
	};

	public Dicttype findByCodeFilterId(Dicttype model) {
		String queryStr = "select dic from Dicttype as dic where dic.typecode =?1 and dic.delStatus= 0 and dic.id!=?2 ";
		List<Dicttype> list = this.em.createQuery(queryStr)
				.setParameter(1, model.getTypecode())
				.setParameter(2, model.getId()).getResultList();
		return list == null || list.size() < 1 ? null : list.get(0);
	};

	public Dicttype findByNameFilterId(Dicttype model) {
		String queryStr = "select dic from Dicttype as dic where dic.typename =?1 and dic.delStatus= 0 and dic.id!=?2 and dic.typegroup.typegroupcode=?3";
		List<Dicttype> list = this.em.createQuery(queryStr)
				.setParameter(1, model.getTypename())
				.setParameter(2, model.getId())
				.setParameter(3, model.getTypegroup().getTypegroupcode())
				.getResultList();
		return list == null || list.size() < 1 ? null : list.get(0);
	};

	/**
	 * 新增硬件类型
	 */
	@Transactional
	public void createDeviceType(Dicttype model) {
		dslservice.setEntityClass(Dicttype.class);
		dslservice.create(model);
		// 新增硬件类型与硬件方案对应关系
		Long typeId = Long.parseLong(model.getOperateType().split(",")[1]);
		DeviceType type = new DeviceType();
		type.setId(typeId);
		DeviceTypeItem typeItem = new DeviceTypeItem();
		typeItem.setDelStatus((short) 0);
		typeItem.setItem(model);
		typeItem.setType(type);
		dslservice.setEntityClass(DeviceTypeItem.class);
		dslservice.create(typeItem);
	};

	/**
	 * 删除硬件类型
	 */
	@Transactional
	public void deleteDeviceType(Dicttype model) {
		dslservice.setEntityClass(Dicttype.class);
		dslservice.update(model);
		// 删除硬件类型与硬件方案对应关系
		String query = "update DeviceTypeItem u set u.delStatus = 1  where u.item.id = ?1";
		this.em.createQuery(query).setParameter(1, model.getId())
				.executeUpdate();
	}

	/**
	 * 常规判重
	 *
	 * @author ytche
	 * @param model
	 * @date 2017年6月9日 下午1:55:46
	 */
	public void checkRepeat(Dicttype model) {
		this.dslservice.setEntityClass(Dicttype.class);
		String query = "from Dicttype as type where type.typename= :name and type.delStatus=0";
		List<Dicttype> list = this.em.createQuery(query)
				.setParameter("name", model.getTypename()).getResultList();
		if (list != null && list.size() > 0) {
			throw new BusinessException("",
					CommonConstants.ERROR_CODE.NAME_ERROR.label(), "名字重复");
		}
		query = "from Dicttype as type where type.typecode=:code and type.delStatus=0";
		list = this.em.createQuery(query)
				.setParameter("code", model.getTypecode()).getResultList();
		if (list != null && list.size() > 0) {
			throw new BusinessException("",
					CommonConstants.ERROR_CODE.TYPECODE_ERROR.label(), "编码重复");
		}
	}

	/**
	 * 用户删除活动类型的时候,校验是否可以删除
	 *
	 * @author ytche
	 * @param model
	 * @date 2017年6月9日 下午5:42:00
	 */
	public void checkDelete(Dicttype model) {
		Typegroup group = model.getTypegroup();
		if (group == null || StringUtils.isBlank(group.getTypegroupcode())) {
			return;
		}
		Boolean isActivityType = group.getTypegroupcode().equals(
				CommonConstants.TYPEGROUP.ACTIVITY_TYPE.lable());
		Boolean isVipLevel = group.getTypegroupcode().equals(
				CommonConstants.TYPEGROUP.VIP_LEVEL.lable());
		if (!(isActivityType || isVipLevel)) {
			return;
		}
		Boolean allowDelete = false;
		if (isActivityType) {
			List<Activity> activities = this.activityService.findNotDelete(
					"type.id", model.getId());
			allowDelete = activities == null || activities.size() < 1;
		}
		if (isVipLevel) {
			allowDelete = this.vipInfoService.checkVipLevelDelete(model);
		}
		if (!allowDelete) {
			throw new BusinessException("",
					CommonConstants.ERROR_CODE.NO_DELETE.label(), "不能删除");
		}
	}

	/**
	 * 获取所有未删除的dicttye
	 *
	 * @author ytche
	 * @return
	 * @date 2017年7月28日 下午4:05:19
	 */
	public List<Dicttype> findAll() {
		String queryStr = "from Dicttype where delStatus=0 ";
		return this.em.createQuery(queryStr).getResultList();
	}
	
	public List<Dicttype> findAll(List<String> groupCodes) {
		String queryStr = "from Dicttype where delStatus=0 and typegroup.typegroupcode in :codes ";
		return this.em.createQuery(queryStr).setParameter("codes", groupCodes).getResultList();
	}
}
